package com.geeke.config.crypto;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson.JSONObject;
import com.geeke.sys.controller.SecurityController;
import com.geeke.sys.entity.Security;
import com.geeke.sys.service.SecurityService;
import com.geeke.utils.AesUtils;
/**
 * 返回的内容加密
 */

@Component
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice<Object>  {

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 获取系统安全配置返回值不加密
        if(returnType.getExecutable().getDeclaringClass() == SecurityController.class
            && "getById".equals(returnType.getExecutable().getName())) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
        Class<? extends HttpMessageConverter<?>> selectedConverterType, 
        ServerHttpRequest request, ServerHttpResponse response) {
        String text = JSONObject.toJSONString(body);
        try {
            Security Security = securityService.get("1");
            if("1".equals(Security.getCryptoFlag())) {
                String key = AesUtils.generateKey();
                response.getHeaders().add("encrypt-key", key);
                return AesUtils.encrypt(text, key, Security.getCryptoIv());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }
}
